package cn.wsalix.shop.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.service.impl.SimpleServiceImpl;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.biz.service.CategoryService;
import cn.wsalix.shop.entity.Product;
import cn.wsalix.shop.entity.ShopInfo;
import cn.wsalix.shop.form.ShopInfoForm;
import cn.wsalix.shop.repository.ShopInfoRepository;
import cn.wsalix.shop.service.ProductService;
import cn.wsalix.shop.service.ShopInfoService;

@Service("productStandard")
public class ShopInfoServiceImpl
		extends
		SimpleServiceImpl<ShopInfoForm, ShopInfoRepository, ShopInfo>
		implements ShopInfoService {
	@Autowired
	private ShopInfoRepository productStandardRepository;
	@Autowired
	private ProductService productService;
	@Autowired
	private CategoryService categoryService;
	@Override
	public String module() {
		return "/shop/info";
	}

	@Override
	public ShopInfoRepository getRepository() {
		return productStandardRepository;
	}

	@Transactional
	@Override
	public ShopInfo add(ShopInfoForm entity) {
		if (entity.getProductId() != null && entity.getProductId() != 0) {
			Product product = productService.findById(entity.getProductId());
			entity.setProduct(product);
		}
		entity.setCode(entity.getCode());
		entity.setName(entity.getName());
		return super.add(entity);
	}

	@Transactional
	@Override
	public ShopInfo edit(ShopInfoForm entity) {
		ShopInfo obj = productStandardRepository.findOne(entity.getId());
		if (entity.getCode() != null && !entity.getCode().trim().equals("")) {
			obj.setCode(entity.getCode());
		}
		if (entity.getName() != null && !entity.getName().trim().equals("")) {
			obj.setName(entity.getName());
		}
		return super.edit(entity);
	}

	@Override
	public Class<ShopInfo> getEntityClazz() {
		return ShopInfo.class;
	}

	@Override
	public Map<String, SearchFilter> buildByForm(ShopInfoForm form) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (form.getProductId() != null && form.getProductId() != 0) {
			filters.put("product.id", new SearchFilter("product.id",
					Operator.EQ, form.getProductId()));
		}		
		return filters;
	}

}
